[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isIPageInfoForEntity } from '@growi/core';
  4. import type {
  5. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  6. } from '@growi/core';
  7. import {
  8. isClient, pagePathUtils, pathUtils,
  9. } from '@growi/core/dist/utils';
  10. import ExtensibleCustomError from 'extensible-custom-error';
  11. import type {
  12. GetServerSideProps, GetServerSidePropsContext,
  13. } from 'next';
  14. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  15. import dynamic from 'next/dynamic';
  16. import Head from 'next/head';
  17. import { useRouter } from 'next/router';
  18. import superjson from 'superjson';
  19. import { useLayoutFluidClassNameByPage, useEditorModeClassName } from '~/client/services/layout';
  20. import { PageView } from '~/components/Page/PageView';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript'; import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsForbidden, useIsSharedUser,
  30. useIsEnabledStaleNotification, useIsIdenticalPath,
  31. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  32. useDefaultIndentSize, useIsIndentSizeForced,
  33. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  34. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  35. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  36. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  37. } from '~/stores/context';
  38. import { useEditingMarkdown } from '~/stores/editor';
  39. import {
  40. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  41. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  42. } from '~/stores/page';
  43. import { useRedirectFrom } from '~/stores/page-redirect';
  44. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  45. import { useSelectedGrant } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  50. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  51. import type { NextPageWithLayout } from './_app.page';
  52. import type { CommonProps } from './utils/commons';
  53. import {
  54. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  55. } from './utils/commons';
  56. declare global {
  57. // eslint-disable-next-line vars-on-top, no-var
  58. var globalEmitter: EventEmitter;
  59. }
  60. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  61. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  62. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  63. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  64. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  65. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  66. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  67. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  68. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  69. const logger = loggerFactory('growi:pages:all');
  70. const {
  71. isPermalink: _isPermalink, isCreatablePage,
  72. } = pagePathUtils;
  73. const { removeHeadingSlash } = pathUtils;
  74. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  75. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  76. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  77. {
  78. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  79. return v?.data != null
  80. && v?.data.toObject != null
  81. && v?.meta != null
  82. && isIPageInfoForEntity(v.meta);
  83. },
  84. serialize: (v) => {
  85. return {
  86. data: superjson.stringify(v.data.toObject()),
  87. meta: superjson.stringify(v.meta),
  88. };
  89. },
  90. deserialize: (v) => {
  91. return {
  92. data: superjson.parse(v.data),
  93. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  94. };
  95. },
  96. },
  97. 'IPageToShowRevisionWithMetaTransformer',
  98. );
  99. // GrowiContextualSubNavigation for NOT shared page
  100. type GrowiContextualSubNavigationProps = {
  101. isLinkSharingDisabled: boolean,
  102. }
  103. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  104. const { isLinkSharingDisabled } = props;
  105. const { data: currentPage } = useSWRxCurrentPage();
  106. return (
  107. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  108. );
  109. };
  110. type Props = CommonProps & {
  111. pageWithMeta: IPageToShowRevisionWithMeta | null,
  112. // pageUser?: any,
  113. redirectFrom?: string;
  114. // shareLinkId?: string;
  115. isLatestRevision?: boolean,
  116. isIdenticalPathPage?: boolean,
  117. isForbidden: boolean,
  118. isNotFound: boolean,
  119. isNotCreatable: boolean,
  120. // isAbleToDeleteCompletely: boolean,
  121. templateTagData?: string[],
  122. templateBodyData?: string,
  123. isSearchServiceConfigured: boolean,
  124. isSearchServiceReachable: boolean,
  125. isSearchScopeChildrenAsDefault: boolean,
  126. isEnabledMarp: boolean,
  127. isSlackConfigured: boolean,
  128. // isMailerSetup: boolean,
  129. isAclEnabled: boolean,
  130. // hasSlackConfig: boolean,
  131. drawioUri: string | null,
  132. noCdn: string,
  133. // highlightJsStyle: string,
  134. isAllReplyShown: boolean,
  135. isContainerFluid: boolean,
  136. editorConfig: EditorConfig,
  137. isEnabledStaleNotification: boolean,
  138. isEnabledAttachTitleHeader: boolean,
  139. // isEnabledLinebreaks: boolean,
  140. // isEnabledLinebreaksInComments: boolean,
  141. adminPreferredIndentSize: number,
  142. isIndentSizeForced: boolean,
  143. disableLinkSharing: boolean,
  144. skipSSR: boolean,
  145. ssrMaxRevisionBodyLength: number,
  146. grantData?: IPageGrantData,
  147. rendererConfig: RendererConfig,
  148. };
  149. const Page: NextPageWithLayout<Props> = (props: Props) => {
  150. // register global EventEmitter
  151. if (isClient() && window.globalEmitter == null) {
  152. window.globalEmitter = new EventEmitter();
  153. }
  154. const router = useRouter();
  155. useCurrentUser(props.currentUser ?? null);
  156. // commons
  157. useEditorConfig(props.editorConfig);
  158. useCsrfToken(props.csrfToken);
  159. useGrowiCloudUri(props.growiCloudUri);
  160. // page
  161. useIsContainerFluid(props.isContainerFluid);
  162. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  163. useIsForbidden(props.isForbidden);
  164. useIsNotCreatable(props.isNotCreatable);
  165. useRedirectFrom(props.redirectFrom ?? null);
  166. useIsSharedUser(false); // this page cann't be routed for '/share'
  167. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  168. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  169. useIsSearchPage(false);
  170. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  171. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  172. useIsSearchServiceReachable(props.isSearchServiceReachable);
  173. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  174. useIsSlackConfigured(props.isSlackConfigured);
  175. // useIsMailerSetup(props.isMailerSetup);
  176. useIsAclEnabled(props.isAclEnabled);
  177. // useHasSlackConfig(props.hasSlackConfig);
  178. // useNoCdn(props.noCdn);
  179. useDefaultIndentSize(props.adminPreferredIndentSize);
  180. useIsIndentSizeForced(props.isIndentSizeForced);
  181. useDisableLinkSharing(props.disableLinkSharing);
  182. useRendererConfig(props.rendererConfig);
  183. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  184. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  185. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  186. useIsAllReplyShown(props.isAllReplyShown);
  187. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  188. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  189. const { pageWithMeta } = props;
  190. const pageId = pageWithMeta?.data._id;
  191. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  192. const revisionBody = pageWithMeta?.data.revision?.body;
  193. useCurrentPathname(props.currentPathname);
  194. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  195. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  196. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  197. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  198. const { mutate: mutateIsNotFound } = useIsNotFound();
  199. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  200. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  201. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  202. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  203. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  204. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  205. useSetupGlobalSocket();
  206. useSetupGlobalSocketForPage(pageId);
  207. const growiLayoutFluidClass = useLayoutFluidClassNameByPage(pageWithMeta?.data);
  208. // Store initial data (When revisionBody is not SSR)
  209. useEffect(() => {
  210. if (!props.skipSSR) {
  211. return;
  212. }
  213. if (currentPageId != null && !props.isNotFound) {
  214. const mutatePageData = async() => {
  215. const pageData = await mutateCurrentPage();
  216. mutateEditingMarkdown(pageData?.revision.body);
  217. };
  218. // If skipSSR is true, use the API to retrieve page data.
  219. // Because pageWIthMeta does not contain revision.body
  220. mutatePageData();
  221. }
  222. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  223. // sync grant data
  224. useEffect(() => {
  225. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  226. mutateSelectedGrant(grantDataToApply);
  227. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  228. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  229. useEffect(() => {
  230. const decodedURI = decodeURI(window.location.pathname);
  231. if (isClient() && decodedURI !== props.currentPathname) {
  232. const { search, hash } = window.location;
  233. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  234. }
  235. }, [props.currentPathname, router]);
  236. // initialize mutateEditingMarkdown only once per page
  237. // need to include useCurrentPathname not useCurrentPagePath
  238. useEffect(() => {
  239. if (props.currentPathname != null) {
  240. mutateEditingMarkdown(revisionBody);
  241. }
  242. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  243. useEffect(() => {
  244. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  245. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  246. useEffect(() => {
  247. mutateCurrentPageId(pageId ?? null);
  248. }, [mutateCurrentPageId, pageId]);
  249. useEffect(() => {
  250. mutateIsNotFound(props.isNotFound);
  251. }, [mutateIsNotFound, props.isNotFound]);
  252. useEffect(() => {
  253. mutateIsLatestRevision(props.isLatestRevision);
  254. }, [mutateIsLatestRevision, props.isLatestRevision]);
  255. useEffect(() => {
  256. mutateTemplateTagData(props.templateTagData);
  257. }, [props.templateTagData, mutateTemplateTagData]);
  258. useEffect(() => {
  259. mutateTemplateBodyData(props.templateBodyData);
  260. }, [props.templateBodyData, mutateTemplateBodyData]);
  261. const title = generateCustomTitleForPage(props, pagePath);
  262. return (
  263. <>
  264. <Head>
  265. <title>{title}</title>
  266. </Head>
  267. <div className={`dynamic-layout-root ${growiLayoutFluidClass} justify-content-between`}>
  268. <nav className="sticky-top">
  269. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  270. </nav>
  271. <DisplaySwitcher
  272. pageView={(
  273. <PageView
  274. pagePath={pagePath}
  275. initialPage={pageWithMeta?.data}
  276. rendererConfig={props.rendererConfig}
  277. />
  278. )}
  279. />
  280. <PageStatusAlert />
  281. </div>
  282. </>
  283. );
  284. };
  285. type LayoutProps = Props & {
  286. children?: ReactNode
  287. }
  288. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  289. const className = useEditorModeClassName();
  290. // init sidebar config with UserUISettings and sidebarConfig
  291. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  292. return (
  293. <BasicLayout className={className}>
  294. {children}
  295. </BasicLayout>
  296. );
  297. };
  298. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  299. return (
  300. <>
  301. <GrowiPluginsActivator />
  302. <DrawioViewerScript />
  303. <Layout {...page.props}>
  304. {page}
  305. </Layout>
  306. <UnsavedAlertDialog />
  307. <DescendantsPageListModal />
  308. <DrawioModal />
  309. <HandsontableModal />
  310. <QuestionnaireModalManager />
  311. <TemplateModal />
  312. <LinkEditModal />
  313. </>
  314. );
  315. };
  316. function getPageIdFromPathname(currentPathname: string): string | null {
  317. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  318. }
  319. class MultiplePagesHitsError extends ExtensibleCustomError {
  320. pagePath: string;
  321. constructor(pagePath: string) {
  322. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  323. this.pagePath = pagePath;
  324. }
  325. }
  326. // apply parent page grant fot creating page
  327. async function applyGrantToPage(props: Props, ancestor: any) {
  328. await ancestor.populate('grantedGroup');
  329. const grant = {
  330. grant: ancestor.grant,
  331. };
  332. const grantedGroup = ancestor.grantedGroup ? {
  333. grantedGroup: {
  334. id: ancestor.grantedGroup.id,
  335. name: ancestor.grantedGroup.name,
  336. },
  337. } : {};
  338. props.grantData = Object.assign(grant, grantedGroup);
  339. }
  340. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  341. const { model: mongooseModel } = await import('mongoose');
  342. const req: CrowiRequest = context.req as CrowiRequest;
  343. const { crowi } = req;
  344. const { revisionId } = req.query;
  345. const Page = crowi.model('Page') as PageModel;
  346. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  347. const { pageService, configManager } = crowi;
  348. let currentPathname = props.currentPathname;
  349. const pageId = getPageIdFromPathname(currentPathname);
  350. const isPermalink = _isPermalink(currentPathname);
  351. const { user } = req;
  352. if (!isPermalink) {
  353. // check redirects
  354. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  355. if (chains != null) {
  356. // overwrite currentPathname
  357. currentPathname = chains.end.toPath;
  358. props.currentPathname = currentPathname;
  359. // set redirectFrom
  360. props.redirectFrom = chains.start.fromPath;
  361. }
  362. // check whether the specified page path hits to multiple pages
  363. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  364. if (count > 1) {
  365. throw new MultiplePagesHitsError(currentPathname);
  366. }
  367. }
  368. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  369. const page = pageWithMeta?.data as unknown as PageDocument;
  370. // add user to seen users
  371. if (page != null && user != null) {
  372. await page.seen(user);
  373. }
  374. // populate & check if the revision is latest
  375. if (page != null) {
  376. page.initLatestRevisionField(revisionId);
  377. props.isLatestRevision = page.isLatestRevision();
  378. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  379. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  380. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  381. }
  382. if (page == null && user != null) {
  383. const templateData = await Page.findTemplate(props.currentPathname);
  384. if (templateData != null) {
  385. props.templateTagData = templateData.templateTags as string[];
  386. props.templateBodyData = templateData.templateBody as string;
  387. }
  388. // apply pagrent page grant
  389. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  390. if (ancestor != null) {
  391. await applyGrantToPage(props, ancestor);
  392. }
  393. }
  394. props.pageWithMeta = pageWithMeta;
  395. }
  396. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  397. const req: CrowiRequest = context.req as CrowiRequest;
  398. const { crowi } = req;
  399. const Page = crowi.model('Page') as PageModel;
  400. const { currentPathname } = props;
  401. const pageId = getPageIdFromPathname(currentPathname);
  402. const isPermalink = _isPermalink(currentPathname);
  403. const page = props.pageWithMeta?.data;
  404. if (props.isIdenticalPathPage) {
  405. props.isNotCreatable = true;
  406. }
  407. else if (page == null) {
  408. props.isNotFound = true;
  409. props.isNotCreatable = !isCreatablePage(currentPathname);
  410. // check the page is forbidden or just does not exist.
  411. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  412. props.isForbidden = count > 0;
  413. }
  414. else {
  415. props.isNotFound = page.isEmpty;
  416. props.isNotCreatable = false;
  417. props.isForbidden = false;
  418. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  419. if (isPermalink && page.isEmpty) {
  420. props.currentPathname = page.path;
  421. }
  422. // /path/to/page ==> /62a88db47fed8b2d94f30000
  423. if (!isPermalink && !page.isEmpty) {
  424. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  425. if (!isToppage) {
  426. props.currentPathname = `/${page._id}`;
  427. }
  428. }
  429. }
  430. }
  431. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  432. // const req: CrowiRequest = context.req as CrowiRequest;
  433. // const { crowi } = req;
  434. // const UserModel = crowi.model('User');
  435. // if (isUserPage(props.currentPagePath)) {
  436. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  437. // if (user != null) {
  438. // props.pageUser = JSON.stringify(user.toObject());
  439. // }
  440. // }
  441. // }
  442. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  443. const req: CrowiRequest = context.req as CrowiRequest;
  444. const { crowi } = req;
  445. const {
  446. searchService, configManager, aclService,
  447. } = crowi;
  448. props.isSearchServiceConfigured = searchService.isConfigured;
  449. props.isSearchServiceReachable = searchService.isReachable;
  450. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  451. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  452. // props.isMailerSetup = mailService.isMailerSetup;
  453. props.isAclEnabled = aclService.isAclEnabled();
  454. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  455. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  456. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  457. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  458. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  459. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  460. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  461. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  462. props.editorConfig = {
  463. upload: {
  464. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  465. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  466. },
  467. };
  468. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  469. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  470. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  471. props.rendererConfig = {
  472. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  473. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  474. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  475. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  476. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  477. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  478. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  479. // XSS Options
  480. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  481. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  482. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  483. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  484. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  485. };
  486. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  487. }
  488. /**
  489. * for Server Side Translations
  490. * @param context
  491. * @param props
  492. * @param namespacesRequired
  493. */
  494. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  495. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  496. props._nextI18Next = nextI18NextConfig._nextI18Next;
  497. }
  498. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  499. const req = context.req as CrowiRequest<IUserHasId & any>;
  500. const { user } = req;
  501. const result = await getServerSideCommonProps(context);
  502. // check for presence
  503. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  504. if (!('props' in result)) {
  505. throw new Error('invalid getSSP result');
  506. }
  507. const props: Props = result.props as Props;
  508. if (props.redirectDestination != null) {
  509. return {
  510. redirect: {
  511. permanent: false,
  512. destination: props.redirectDestination,
  513. },
  514. };
  515. }
  516. if (user != null) {
  517. props.currentUser = user.toObject();
  518. }
  519. try {
  520. await injectPageData(context, props);
  521. }
  522. catch (err) {
  523. if (err instanceof MultiplePagesHitsError) {
  524. props.isIdenticalPathPage = true;
  525. }
  526. else {
  527. throw err;
  528. }
  529. }
  530. await injectRoutingInformation(context, props);
  531. injectServerConfigurations(context, props);
  532. await injectNextI18NextConfigurations(context, props, ['translation']);
  533. return {
  534. props,
  535. };
  536. };
  537. export default Page;